package com.example.demo.db;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.mp.entity.User;
import com.example.demo.mp.mapper.UserMapper;
import com.example.demo.mp.service.UserService;
import com.example.demo.threads.BatchSqlThread;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.stream.IntStream;
import java.util.stream.Stream;

@Service
@Slf4j
public class DataService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserService userService;
    @Autowired
    @Qualifier("demoExecutor")
    private ExecutorService demoExecutor;

    private List<User> synchronizedList;
    @Value("${generate-count:10000}")
    private int generateCount;
    @Value("${batch-size:1000}")
    private int batchSize;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Async
    public void mockData() {
        log.info("开始造数据...");
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().orderByDesc(User::getId).last("limit 1");

        synchronizedList = Collections.synchronizedList(new ArrayList<>());
        IntStream.range(0, generateCount).parallel().forEach((atomicInteger) -> {
            User entry = new User();
            entry.setName("name" + atomicInteger);
            entry.setEmail("email" + atomicInteger);
            entry.setAge(atomicInteger);
            synchronizedList.add(entry);
        });
        log.info("造数据结束...");
        log.info("开始insert...");
        List<List<User>> split = Collections.synchronizedList(CollectionUtil.split(synchronizedList, batchSize));
        CountDownLatch countDownLatch = new CountDownLatch(split.size());
        Stream.iterate(0, integer -> integer + 1)
                .limit(split.size())
                .parallel()
                .forEach((list) -> {
                    List<User> users = split.get(list);
                    BatchSqlThread batchSqlThread = new BatchSqlThread();
                    batchSqlThread.setUserList(users);
                    batchSqlThread.setUserService(userService);
                    batchSqlThread.setCountDownLatch(countDownLatch);
                    demoExecutor.execute(batchSqlThread);
                });
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            log.info("finally...");
            demoExecutor.shutdown();
        }
    }
}
